import router from "@/router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";
const whiteList = ["/login", "/404", "/warehouse-Bintan"];

router.beforeEach(async (to, from, next) => {
  nprogress.start();

  try {
    if (store.getters.token) {
      // 如果要访问的是登录页，重定向到首页
      if (to.path === "/login") {
        next("/");
        nprogress.done();
        return;
      }

      // 如果还没有获取用户信息，先获取用户信息
      if (store.getters.userInfo.length === 0) {
        try {
          const menus = await store.dispatch("user/getUserInfo");
          const routes = await store.dispatch("permission/filterRoutes", menus);

          // 添加动态路由
          router.addRoutes([
            ...routes,
            { path: "*", redirect: "/404", hidden: true },
          ]);
          next(to.path); // 相当于跳到对应的地址  相当于多做一次跳转 为什么要多做一次跳转
        } catch (error) {
          console.error("权限获取失败:", error);
          await store.dispatch("user/logout");
          next("/login");
          nprogress.done();
        }
      } else {
        // 已经有用户信息了
        next();
      }
    } else {
      // 没有token的处理逻辑保持不变
      if (whiteList.includes(to.path)) {
        next();
      } else {
        next("/login");
        nprogress.done();
      }
    }
  } catch (error) {
    console.error("路由守卫错误:", error);
    nprogress.done();
  }
});

/** *
 * 后置守卫
 * **/
router.afterEach(() => {
  nprogress.done();
});
